package com.hanter.android.radwidget.statusbar;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 小米MIUI状态栏适配
 * 参考：
 */
public class MIUIAdapter implements StatusBarModeAdapter {
    @Override
    public boolean isSupportLightMode() {
        return false;
    }

    @Override
    public boolean setStatusBarMode(Window window, boolean lightMode) {
        boolean result = reflectLightMode(window, lightMode);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int vis = window.getDecorView().getSystemUiVisibility();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (lightMode) {
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            window.getDecorView().setSystemUiVisibility(vis);
            result = true;
        }
        return result;
    }

    private boolean reflectLightMode(Window window, boolean lightMode) {
        boolean result = false;
        Class<? extends Window> clazz = window.getClass();
        try {
            int darkModeFlag;
            @SuppressLint("PrivateApi")
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(window, lightMode ? darkModeFlag : 0, darkModeFlag);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
